//接收端
#include <QuickEspNow.h> 
#include <WiFi.h>
#include <BluetoothSerial.h>

BluetoothSerial SerialBT;

// 定义数据结构（需与发送端一致）
typedef struct {
  uint8_t message;
  uint16_t counter;
} RecvData;

#define GPIO4_PIN 4

// 防抖变量
const unsigned long gpio4Debounce = 200;//两次颠球的最短时间
static const uint8_t channel = 5; //通道
uint16_t count=65535;


// ----------------------------------------------
// QuickEspNow 接收回调函数（严格匹配库的签名）
// ----------------------------------------------
void onDataReceived(const uint8_t* srcAddress, const uint8_t* data, size_t len, int rssi, bool isBroadcast) {
  if (len >= sizeof(RecvData)) { // 校验数据长度
    RecvData* recvData = (RecvData*)data;
    Serial.printf("QuickEspNow 收到数据: " MACSTR, MAC2STR(srcAddress));
    Serial.printf("计数=%d, RSSI=%d\n", recvData->counter, rssi);
    if (count==recvData->counter){
      Serial.println("序号重复,不发送蓝牙");
      return;
    }
    count=recvData->counter;

    // 通过蓝牙发送 0xAA
    SerialBT.write(0xAA);
    Serial.println("蓝牙已发送: 0xAA (QuickEspNow 触发)");
  }
}

// ----------------------------------------------
// 初始化设置
// ----------------------------------------------
void setup() {
  Serial.begin(115200);
  pinMode(GPIO4_PIN, INPUT_PULLDOWN);

  // 初始化蓝牙
  SerialBT.begin("VolleyballCounter");
  Serial.println("蓝牙已启动，名称: VolleyballCounter");
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());

  WiFi.mode (WIFI_MODE_STA);
  WiFi.disconnect (false, true);
  quickEspNow.setWiFiBandwidth(WIFI_IF_AP, WIFI_BW_HT20); 
  quickEspNow.onDataRcvd(onDataReceived);
  quickEspNow.begin(channel, WIFI_IF_STA);
  Serial.printf("当前quickEspNow信道: %d\n", WiFi.channel()); // 应为 2
}

// ----------------------------------------------
// 主循环（GPIO4 检测）
// ----------------------------------------------
void loop() {
  /*bool currentGpio4State = digitalRead(GPIO4_PIN);
  if (currentGpio4State == HIGH && lastGpio4State == LOW) {
    SerialBT.write(0xBB);
    Serial.println("蓝牙已发送: 0xBB (GPIO4 触发)");
  }
  lastGpio4State = currentGpio4State;*/
  if (digitalRead(GPIO4_PIN) == HIGH) {
    SerialBT.write(0xBB);
    Serial.println("蓝牙已发送: 0xBB (GPIO4 触发)");
    //等待低电平
    while (digitalRead(GPIO4_PIN) == HIGH) {
      delay(10);
    }
    delay(gpio4Debounce);//两次颠球的最短时间，小于这个时间的不计数
  }

  //delay(10);
}